﻿using System.Collections.Generic;
using System.IO;
using Compass.Wasm.Shared.Categories;
using Compass.Wasm.Shared.Extensions;
using Application = Microsoft.Office.Interop.Excel.Application;

namespace Compass.Wpf.ViewModels.Settings;

public class AccCutListViewModel : NavigationViewModel
{
    /* SQL
     * insert into AccCutLists (Id,AccType,PartDescription,Length,Width,Thickness,Quantity,Material,PartNo,IsDeleted,CreationTime)
    values 
    ('D22D2BD4-BE12-421C-2665-4C1A24A5D016','UCWUVRACK4S_天花UV灯','UCW特殊UVR骨架后S',804,73,1,1,'1.0 mm SS304 2B/2B','UCWUVRACK4S_6200300102',0,'2023-10-11 15:21:45.4102842')
     */
    #region ctor
    private readonly IAccCutListService _accCutListService;
    public AccCutListViewModel(IContainerProvider provider) : base(provider)
    {
        _accCutListService = provider.Resolve<IAccCutListService>();
        AccCutListDto=new AccCutListDto();

        AddAccCutListCommand = new DelegateCommand(AddAccCutList);
        UpdateAccCutListCommand = new DelegateCommand<AccCutListDto>(UpdateAccCutList);
        SaveAccCutListCommand = new DelegateCommand(SaveAccCutList);

        OpenCsvCommand = new DelegateCommand(OpenCsv);
        UpdateCommand = new DelegateCommand(Update);
        UpdateRoles = "admin";
    }
    public DelegateCommand AddAccCutListCommand { get; }
    public DelegateCommand<AccCutListDto> UpdateAccCutListCommand { get; }
    public DelegateCommand SaveAccCutListCommand { get; }

    public DelegateCommand OpenCsvCommand { get; }
    public DelegateCommand UpdateCommand { get; }
    #endregion

    #region 右侧展开栏属性
    private bool isRightDrawerOpen;
    /// <summary>
    /// 右侧窗口是否展开
    /// </summary>
    public bool IsRightDrawerOpen
    {
        get => isRightDrawerOpen;
        set { isRightDrawerOpen = value; RaisePropertyChanged(); }
    }
    private string rightDrawerTitle = null!;
    public string RightDrawerTitle
    {
        get => rightDrawerTitle;
        set { rightDrawerTitle = value; RaisePropertyChanged(); }
    }

    #endregion

    #region 属性
    private string[] accTypes = null!;
    public string[] AccTypes
    {
        get => accTypes;
        set { accTypes = value; RaisePropertyChanged(); }
    }

    private AccCutListDto accCutListDto;
    public AccCutListDto AccCutListDto
    {
        get => accCutListDto;
        set { accCutListDto = value; RaisePropertyChanged(); }
    }

    public ObservableRangeCollection<AccCutListDto> AccCutListDtos { get; } = new();
    public ObservableRangeCollection<AccCutListDto> FilterAccCutListDtos { get; } = new();
    private string search;
    /// <summary>
    /// 搜索条件属性
    /// </summary>
    public string Search
    {
        get => search;
        set
        {
            search = value; RaisePropertyChanged();
            Filter();
        }
    }
    private string updateRoles;
    public string UpdateRoles
    {
        get => updateRoles;
        set { updateRoles = value; RaisePropertyChanged(); }
    }


    #endregion

    #region 增删改查，打开CSV文件，更新列表
    private void AddAccCutList()
    {
        AccCutListDto=new AccCutListDto();

        IsRightDrawerOpen = true;
        RightDrawerTitle = "添加切割清单";
    }

    private void UpdateAccCutList(AccCutListDto obj)
    {
        AccCutListDto=obj;

        IsRightDrawerOpen = true;
        RightDrawerTitle = "修改切割清单";
    }

    //private async void DeleteLocation(LocationDto obj)
    //{
    //    //删除询问
    //    var dialogResult = await DialogHost.Question("删除确认", $"确认删除库位：{obj.Name}, {obj.Remarks} 吗?");
    //    if (dialogResult.Result != ButtonResult.OK) return;
    //    await _locationService.DeleteAsync(obj.Id.Value);
    //    await GetDataAsync();
    //}

    private async void SaveAccCutList()
    {
        //数据验证
        if (string.IsNullOrWhiteSpace(AccCutListDto.PartNo))
        {
            //发送提示
            Aggregator.SendMessage("零件号不能为空");
            return;
        }

        try
        {
            if (AccCutListDto.Id != null && AccCutListDto.Id.Value != Guid.Empty)
            {
                AccCutListDto.PartNo =AccCutListDto.PartNo.ToUpper();
                await _accCutListService.UpdateAsync(AccCutListDto.Id.Value, AccCutListDto);
                Aggregator.SendMessage($"切割清单：{AccCutListDto.PartNo}修改成功！");
                AccCutListDto.Id=Guid.Empty;
            }
            else
            {
                AccCutListDto.PartNo =AccCutListDto.PartNo.ToUpper();
                //var dto = await _accCutListService.GetSingleByNameAsync(LocationDto.Name);
                //if (dto.Status)
                //{
                //    Aggregator.SendMessage($"请不要重复添加，库位：{LocationDto.Name}！");
                //    return;
                //}
                await _accCutListService.AddAsync(AccCutListDto);
                Aggregator.SendMessage($"切割清单：{AccCutListDto.PartNo}添加成功！");
                AccCutListDto.Id=Guid.Empty;
            }
            IsRightDrawerOpen = false;
            GetDataAsync();
        }
        catch (Exception e)
        {
            //发送错误报告
            Aggregator.SendMessage(e.Message);
        }
    }


    private void OpenCsv()
    {
        var path = Path.Combine(Environment.CurrentDirectory, "AccCutList.csv");
        var excelApp = new Application();
        excelApp.Workbooks.Open(path);
        excelApp.Visible=true;
    }
    private async void Update()
    {
        var path = Path.Combine(Environment.CurrentDirectory, "AccCutList.csv");
        List<AccCutListString> accCutLists;
        try
        {
            accCutLists= path.GetRecords<AccCutListString>();
        }
        //StreamReader的异常
        catch (Exception e)
        {
            Aggregator.SendMessage($"请关闭Excel后再执行更新，{e.Message}");
            return;
        }
        var dtos = (await _accCutListService.GetAllAsync()).Result;
        foreach (var item in accCutLists)
        {
            //判断文件号是否相同，保证文件必须唯一
            var dto = dtos.FirstOrDefault(x => x.PartNo.Equals(item.PartNo)) ??
                      new AccCutListDto { Id = Guid.Empty };
            dto.AccType = item.AccType.ToEnum<AccType_e>();
            dto.PartDescription=item.PartDescription;
            dto.Length = item.Length.ToDouble();
            dto.Width = item.Width.ToDouble();
            dto.Thickness=item.Thickness.ToDouble();
            dto.Quantity = item.Quantity.ToInt();
            dto.Material = item.Material;
            dto.PartNo=item.PartNo;
            dto.BendingMark=item.BendingMark;

            if (dto.Id == Guid.Empty)
            {
                await _accCutListService.AddAsync(dto);
            }
            else
            {
                await _accCutListService.UpdateAsync(dto.Id.Value, dto);
            }
        }

        Aggregator.SendMessage("更新完毕！");
        GetDataAsync();
    }

    private void Filter()
    {
        FilterAccCutListDtos.ReplaceRange(
            AccCutListDtos.Where(x =>
                string.IsNullOrEmpty(Search)||
                x.AccType.ToString().Contains(Search, StringComparison.OrdinalIgnoreCase)||
                (!string.IsNullOrEmpty(x.PartDescription)&& x.PartDescription.Contains(Search, StringComparison.OrdinalIgnoreCase))||
                (!string.IsNullOrEmpty(x.PartNo)&&x.PartNo!.Contains(Search, StringComparison.OrdinalIgnoreCase))));
    }
    #endregion

    #region 导航初始化
    private void GetEnumNames()
    {
        //初始化一些枚举值
        AccTypes=Enum.GetNames(typeof(AccType_e));
    }
    private async void GetDataAsync()
    {
        var result = await _accCutListService.GetAllAsync();
        if (!result.Status) return;
        AccCutListDtos.ReplaceRange(result.Result);
        Filter();
    }
    public override void OnNavigatedTo(NavigationContext navigationContext)
    {
        base.OnNavigatedTo(navigationContext);
        GetEnumNames();
        GetDataAsync();
    }
    #endregion
}